/**
 * 删除上传的图片
 */
function deleteCover(value) {
    $("#" + value).remove();
}

/**
 * 主页
 */
define(['jquery',
    'base',
    'baseUtils',
    'css!global/plugins/fileInput/fileinput.min.css',
    'plugins/fileInput/fileinput.min',
    'plugins/address/distpicker',
    'plugins/address/distpicker.data'
], function ($, base, baseUtils, _, _, _) {
    //默认加载基础库
    base();
    //执行
    return {
        info: function () {

            $("#saveUserExtendForm").validate({
                rules: {
                    realName: {
                        required: true
                    },
                    avatar: {
                        required: true
                    },
                    birthday: {
                        required: true,
                        date: true
                    },
                    age: {
                        required: true,
                        digits: true
                    },
                    province: {
                        required: true
                    },
                    city: {
                        required: true
                    },
                    area: {
                        required: true
                    },
                    address: {
                        required: true,
                        rangelength: [2, 100]
                    }

                },
                messages: {
                    realName: {
                        required: errorIcon + "名称不能为空"
                    },
                    avatar: {
                        required: errorIcon + "图片不能为空"
                    },
                    birthday: {
                        required: errorIcon + "日期不能为空",
                        birthday: $.validator.format(errorIcon + "格式错误，范例：2017-08-10")
                    },
                    age: {
                        required: errorIcon + "不能为空",
                        digits: $.validator.format(errorIcon + "只能输入数字。")
                    },
                    province: {
                        required: errorIcon + "不能为空"
                    },
                    city: {
                        required: errorIcon + "不能为空"
                    },
                    area: {
                        required: errorIcon + "不能为空"
                    },
                    address: {
                        required: errorIcon + "详细地址不能为空",
                        rangelength: $.validator.format(errorIcon + "字数在2-100个之间。")
                    }
                }
            });

            $("#avatarUploader").fileinput({
                //设置语言
                language: 'zh',
                //上传的地址
                uploadUrl: '/common/uploader/index',
                method: 'post',
                msgPlaceholder: '请选择头像',
                //附加属性(0图片，1文件)
                uploadExtraData: {filesType: 0},
                //上传类型
                allowedFileExtensions: ['jpg', 'gif', 'png', 'jpeg'],
                //是否显示图片展示框
                showPreview: false,
                //是否显示上传按钮
                showUpload: true,
                showCancel: false,
                //是否显示上传输入框
                showCaption: true,
                //是否显示删除键
                showRemove: true,
                //浏览图标
                browseIcon: '<i class="iconfont icon-wenjianjia"></i>&nbsp;',
                //浏览样式
                browseClass: 'btn btn-success btn-outline',
                //上传图标
                uploadIcon: '<i class="iconfont icon-upload"></i>&nbsp;',
                //上传样式
                uploadClass: 'btn btn-success btn-outline',
                //移除图标
                removeIcon: '<i class="iconfont icon-remove"></i>&nbsp;',
                //移除样式
                removeClass: 'btn btn-info btn-outline',
                //单位为kb，(30M)如果为0表示不限制文件大小
                maxFileSize: 10720,
                //错误显示位置
                elErrorContainer: "#file-upload-error",
                //错误显示位置节点样式
                msgErrorClass: 'alert alert-block alert-danger',
                //验证数量
                validateInitialCount: true
            }).on("fileuploaded", function (event, data) {
                if (data.response !== null && data.response.status) {
                    $("#avatar").val(data.response.url);
                    $("#avatarImage").attr("src", data.response.domain + data.response.url);
                } else {
                    $("#file-upload-error").text(data.response.message);
                }
            });

            /**
             * 提交用户扩展信息
             */

            $("#submitUserExtend").on('click', function () {
                var valid = $("#saveUserExtendForm").valid();
                if (valid) {
                    $.baseUtils.ajax({
                        url: "/user/info/save",
                        data: $("#saveUserExtendForm").serialize(),
                        context: "项目",
                        text: "提交",
                        skip: "/user/auth/wait",
                        skipTime: 3000,
                        refresh: true
                    });
                }
            })
        },
        auth: function (userType) {
            //类型
            var idName, certName;
            if (userType === 1 || userType === 2) {
                idName = "《身份证正反面》照片";
                certName = "《技能或荣誉证书》照片，可上传多张。";

            } else {
                idName = "《营业执照》照片";
                certName = "《资质或荣誉证书》照片，可上传多张。";
            }

            //资质证书
            doUploader("#certUploader", "请选择" + certName, "#cert-upload-error", "#cert-upload-success", "certList");
            //身份证
            doUploader("#idUploader", "请选择" + idName, "#id-upload-error", "#id-upload-success", "idList");

            function doUploader(node, placeholder, elErrorContainer, successContainer, listName) {
                return $(node).fileinput({
                    //设置语言
                    language: 'zh',
                    //上传的地址
                    uploadUrl: '/common/uploader/index',
                    method: 'post',
                    msgPlaceholder: placeholder,
                    //附加属性(0图片，1文件)
                    uploadExtraData: {filesType: 0},
                    //上传类型
                    allowedFileExtensions: ['jpg', 'gif', 'png', 'jpeg'],
                    //是否显示图片展示框
                    showPreview: false,
                    //是否显示上传按钮
                    showUpload: true,
                    showCancel: false,
                    //是否显示上传输入框
                    showCaption: true,
                    //是否显示删除键
                    showRemove: true,
                    //浏览图标
                    browseIcon: '<i class="iconfont icon-wenjianjia"></i>&nbsp;',
                    //浏览样式
                    browseClass: 'btn btn-success btn-outline',
                    //上传图标
                    uploadIcon: '<i class="iconfont icon-upload"></i>&nbsp;',
                    //上传样式
                    uploadClass: 'btn btn-success btn-outline',
                    //移除图标
                    removeIcon: '<i class="iconfont icon-remove"></i>&nbsp;',
                    //移除样式
                    removeClass: 'btn btn-info btn-outline',
                    //单位为kb，(30M)如果为0表示不限制文件大小
                    maxFileSize: 10720,
                    //错误显示位置
                    elErrorContainer: elErrorContainer,
                    //错误显示位置节点样式
                    msgErrorClass: 'alert alert-block alert-danger',
                    //验证数量
                    validateInitialCount: true
                }).on("fileuploaded", function (event, data) {
                    if (data.response !== null && data.response.status) {
                        $(successContainer).append("<div class=\"col-xs-12 col-sm-6 col-md-3 mb10\" id=\"" + data.response.nodeId + "\"><div class=\"thumbnail uploadImageShow\"><input type=\"hidden\" name=\"" + listName + "\" value=\"" + data.response.url + "\"><a href=\"" + data.response.domain + data.response.url + "\" target='_blank'><img src=\"" + data.response.domain + data.response.url + "\"></a></div><div class=\"caption\"><div class=\"btn btn-block btn-danger deletetCover\" onclick=\"deleteCover('" + data.response.nodeId + "')\">删除</div></div></div>");
                    } else {
                        $(elErrorContainer).text(data.response.message);
                    }
                });
            }

            $("#saveUserCertForm").validate({
                rules: {
                    realName: {
                        required: true
                    },
                    number: {
                        required: true,
                        minlength: 5
                    }
                },
                messages: {
                    realName: {
                        required: errorIcon + "名称不能为空"
                    },
                    number: {
                        required: errorIcon + "证件号码不能为空",
                        minlength: $.validator.format(errorIcon + "证件号码最少5位。")
                    }
                }
            });


            $("#submitUserCert").on('click', function () {
                var valid = $("#saveUserCertForm").valid();
                //身份证
                var idCount = $("#saveUserCertForm").find("input[name='idList']").length;
                var authStatus = $("#isAuth").val() == 1;
                if (authStatus || idCount > 0) {
                    idCount = 1;
                    $("#id-error").text("");
                    $("#id-box").removeClass("has-error").addClass("has-success");
                } else {
                    $("#id-box").addClass("has-error");
                    $("#id-error").text("证件不能为空！");
                }
                //证书
                var certCount = $("#saveUserCertForm").find("input[name='certList']").length;
                if (certCount > 0) {
                    certCount = 1;
                    $("#cert-error").text("");
                    $("#cert-box").removeClass("has-error").addClass("has-success");
                } else {
                    $("#cert-box").addClass("has-error");
                    $("#cert-error").text("证件不能为空！");
                }

                if (valid && idCount > 0 && certCount > 0) {
                    $.ajax({
                        url: "/user/auth/save",
                        method: "POST",
                        dataType: "json",
                        data: $("#saveUserCertForm").serialize(),
                        success: function (data) {
                            if (data.success) {
                                if ($("#isAuth").val() == 0 && $("#isComplete").val() == 0) {
                                    window.location = "/user/info/index";
                                } else {
                                    window.location = "/user/index";
                                }
                            }
                        },
                        error: function (jqXHR) {
                            msgTool.error(jqXHR.status + " (" + jqXHR.statusText + ")", "错误提示");
                        }
                    });
                }
            })


        },
        password: function () {
            /**
             * 仿刷新：检测是否存在cookie
             */
            if ($.cookie("passwordCode")) {
                var count = $.cookie("passwordCode");
                var btn = $("#getCode");
                btn.text(count + '秒后可重新获取').attr('disabled', true).css('cursor', 'not-allowed');
                var resend = setInterval(function () {
                    count--;
                    if (count > 0) {
                        btn.text(count + '秒后可重新获取').attr('disabled', true).css('cursor', 'not-allowed');
                        $.cookie("passwordCode", count, {path: '/', expires: (1 / 86400) * count});
                    } else {
                        clearInterval(resend);
                        btn.text("获取验证码").removeClass('disabled').removeAttr('disabled style');
                    }
                }, 1000);
            }


            /**
             * 点击改变按钮状态，已经简略掉ajax发送短信验证的代码
             */
            $("#getCode").on('click', function () {
                var phoneNumber = $("#phone").val();
                if (phoneNumber === null || phoneNumber === '') {
                    var phone = $("#phone").parent();
                    phone.removeClass("has-success").addClass("has-error");
                    phone.find(".help-block").remove();
                    phone.append("<span class=\"help-block pull-left\"><i class=\"iconfont icon-error\"></i>请输入手机号码</span>");
                    return;
                }

                /**
                 * 执行发送
                 */
                $.ajax({
                    url: "/user/sendForgetMobile",
                    method: "POST",
                    dataType: "json",
                    data: {mobile: phoneNumber},
                    success: function (data) {
                        if (data.success) {
                            msgTool.success(data.msg, "发送成功");
                        } else {
                            msgTool.error(data.msg, "发送失败");
                        }
                    },
                    error: function (jqXHR) {
                        msgTool.error(jqXHR.status + " (" + jqXHR.statusText + ")", "错误提示");
                    }
                });


                /**
                 * 操作按钮
                 */
                var btn = $(this);
                var count = 60;
                var resend = setInterval(function () {
                    count--;
                    if (count > 0) {
                        btn.text(count + "秒后可重新获取");
                        $.cookie("passwordCode", count, {path: '/', expires: (1 / 86400) * count});
                    } else {
                        clearInterval(resend);
                        btn.text("获取验证码").removeAttr('disabled style');
                    }
                }, 1000);
                btn.attr('disabled', true).css('cursor', 'not-allowed');
            });


            //找回密码
            $("#passwordForm").validate({
                rules: {
                    phone: {
                        required: true,
                        minlength: 11,
                        valiPhone: true
                    },
                    password: {
                        required: true,
                        rangelength: [6, 18],
                        valiPassword: true
                    },
                    confirmPassword: {
                        required: true,
                        rangelength: [6, 18],
                        valiPassword: true,
                        equalTo: "#password"
                    },
                    code: {
                        rangelength: [6, 6],
                        required: true
                    }

                },
                messages: {
                    phone: {
                        required: errorIcon + "请输入手机号",
                        minlength: $.validator.format(errorIcon + "手机号最少要输入{0}个字符。"),
                        remote: $.validator.format(errorIcon + "手机号“{0}”已经被占用。")
                    },
                    password: {
                        required: errorIcon + "请输入密码",
                        rangelength: $.validator.format(errorIcon + "密码最少要输入{0}个字符。")
                    },
                    confirmPassword: {
                        required: errorIcon + "请再次输入密码",
                        rangelength: $.validator.format(errorIcon + "密码最少要输入{0}个字符。"),
                        equalTo: errorIcon + "两次密码不相同。"
                    },
                    code: {
                        required: errorIcon + "请输入短信验证码",
                        rangelength: $.validator.format(errorIcon + "短信验证码为{0}数字。"),
                        remote: $.validator.format(errorIcon + "验证码错误")
                    }
                }
            });

            //回车提交
            $(document).keyup(function (event) {
                if (event.keyCode === 13) {
                    $("#doSubmit").trigger("click");
                }
            });
            //点击提交
            $("#doSubmit").on('click', function () {
                var valid = $("#passwordForm").valid();
                if (valid) {
                    $.ajax({
                        url: "/user/resetPassword",
                        type: 'POST',
                        data: $("#passwordForm").serialize(),
                        dataType: "JSON",
                        cache: false,
                        async: false,
                        beforeSend: function () {
                            //触发ajax请求开始时执行
                            $("#doSubmit").text('提交中...');
                            $("#doSubmit").attr('disabled', 'disabled');
                        },
                        success: function (data) {
                            if (data.success) {
                                $("#messageCode").text("密码重置成功，请重新登录！");
                                $("#passwordForm")[0].reset();
                            } else {
                                $("#messageCode").text(data.msg);
                            }
                        },
                        error: function () {
                            $("#messageCode").text("重置密码失败，请稍后重试！");
                        },
                        complete: function () {
                            $("#doSubmit").text("提交");
                            $("#doSubmit").removeAttr('disabled');
                        }
                    });
                }
            });
        },
        authWait: function () {

        }
    };
});
